<?php

namespace app\admin\controller;

use app\common\model\Student as studentModel;
use app\common\model\UserStudent;
use app\common\model\Withdrawal as WithdrawalModel;
use app\common\model\User as UserModel;
use app\common\model\MoneyLog as MoneyLogModel;
use app\service\PayService;

class Finance extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /* 佣金流水 */
    public function moneylog()
    {
        if(request()->isPost()){
            $where = [
                'type' => 1
            ];
            if ($this->mall_id != 0) {
                $where['mall_id'] = $this->mall_id;
            }
            $input = input();
            if ($input['uid']) {
                $where['uid'] = $input['uid'];
            }
            if ($input['sid']) {
                $where['sid'] = $input['sid'];
            }
            if ($input['order_id']) {
                $where['order_id'] = $input['order_id'];
            }
            $page = max($input['page'], 1);
            $size = 50;
            $list = MoneyLogModel::getPage($where, $page, $size, 'id desc');
            $total = MoneyLogModel::getCount($where);
            if (!$list) {
                return returnJson(0, '', [
                    'list' => [],
                    'size' => $size,
                    'total' => 0
                ]);
            }
            foreach ($list as $k => $v) {
                $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
            }
            return returnJson(0, '', [
                'list' => $list,
                'size' => $size,
                'total' => $total,
                'page' => $page
            ]);
        }
    }

    /* 积分流水 */
    public function scorelog()
    {
        if(request()->isPost()){
            $where = [
                'type' => 2
            ];
            if ($this->mall_id != 0) {
                $where['mall_id'] = $this->mall_id;
            }
            $input = input();
            if ($input['uid']) {
                $where['uid'] = $input['uid'];
            }
            if ($input['sid']) {
                $where['sid'] = $input['sid'];
            }
            if ($input['order_id']) {
                $where['order_id'] = $input['order_id'];
            }
            $page = max($input['page'], 1);
            $size = 50;
            $list = MoneyLogModel::getPage($where, $page, $size, 'id desc');
            $total = MoneyLogModel::getCount($where);
            if (!$list) {
                return returnJson(0, '', [
                    'list' => [],
                    'size' => $size,
                    'total' => 0
                ]);
            }
            foreach ($list as $k => $v) {
                $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
                $list[$k]['studentInfo'] = \app\common\model\Student::getOne(['id' => $v['sid']], 'name,id');
            }
            return returnJson(0, '', [
                'list' => $list,
                'size' => $size,
                'total' => $total,
                'page' => $page
            ]);
        }
    }

    /* 充值币 */
    public function cashlog()
    {
        $where = [
            'type' => 3
        ];
        $input = input();
        if ($input['uid']) {
            $where['uid'] = $input['uid'];
        }
        if ($input['order_id']) {
            $where['order_id'] = $input['order_id'];
        }
        $page = max($input['page'], 1);
        $size = 50;
        $list = MoneyLogModel::getPage($where, $page, $size, 'id desc');
        $total = MoneyLogModel::getCount($where);
        if (!$list) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach ($list as $k => $v) {
            $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
        }
        return returnJson(0, '', [
            'list' => $list,
            'size' => $size,
            'total' => $total,
            'page' => $page
        ]);
    }

    /* 提现记录 */
    public function withdrawal()
    {
        $where = [];
        $input = input();
        if ($input['uid']) {
            $where['uid'] = $input['uid'];
        }
        $page = max($input['page'], 1);
        $size = 50;
        $list = WithdrawalModel::getPage($where, $page, $size, 'id desc');
        $total = WithdrawalModel::getCount($where);

        if (!$list) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach ($list as $k => $v) {
            $list[$k]['userInfo'] = UserModel::getOne(['id' => $v['uid']], 'nickname,id');
            if ($v['status'] == 1) {
                $status_text = '待处理';
            } elseif ($v['status'] == 2) {
                $status_text = '已处理';
            } else {
                $status_text = '已退回';
            }
            $list[$k]['status_text'] = $status_text;
        }
        return returnJson(0, '', [
            'list' => $list,
            'size' => $size,
            'total' => $total,
            'page' => $page
        ]);
    }

    /* 充值佣金 */
    public function chargemoney()
    {
        $input = input();
        if (!$input['number'] || !is_numeric($input['number'])) {
            return returnJson(1, '金额填写错误');
        }
        if (!$input['uid']) {
            return returnJson(1, '请填写用户ID');
        }
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        $userInfo = UserModel::getOne(['id' => $input['uid']]);
        if (!$userInfo) {
            return returnJson(1, '用户不存在');
        }
        $key = "charge-{$input['uid']}-{$input['number']}";
        $cache = cache($key);
        if ($cache) {
            return returnJson(1, '为防止重复充值,请1分钟后再试');
        }
        cache($key, 1, 60);
        UserModel::changeMoney($input['uid'], 1, $input['number'], $input['note'], '', [
            'manager_name' => $this->manager['name'],
            'is_charge' => 1
        ]);
        return returnJson(0, '充值成功');
    }

    /* 充值积分 */
    public function chrgescore()
    {
        $input = input();
        if (!$input['number'] || !is_numeric($input['number'])) {
            return returnJson(1, '金额填写错误');
        }
        if (!$input['uid']) {
            return returnJson(1, '请填写用户ID');
        }
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        if ($input['uid']) {
            $userInfo = UserModel::getOne(['id' => $input['uid']]);
            if (!$userInfo) {
                return returnJson(1, '用户不存在');
            }
        }
        if ($input['sid']) {
            $studentInfo = \app\common\model\Student::getOne(['id' => $input['sid']]);
            if (!$studentInfo) {
                return returnJson(1, '学员不存在');
            }
            $userStudent = UserStudent::getOne(['uid' => $input['uid'], 'sid' => $input['sid']]);
            if (!$userStudent) {
                return returnJson(1, '该家长未绑定该学员');
            }
        }
        $key = "charge-{$input['uid']}-{$input['sid']}-{$input['number']}";
        $cache = cache($key);
        if ($cache) {
            return returnJson(1, '为防止重复充值,请1分钟后再试');
        }
        cache($key, 1, 60);
        UserModel::changeMoney($input['uid'], 2, $input['number'], $input['note'], '', [
            'manager_name' => $this->manager['name'],
            'is_charge' => 1
        ], $input['sid']);
        return returnJson(0, '充值成功');
    }


    /* 充值积分 */
    public function chrgeScoreCla()
    {
        $input = input();
        if (!$input['number'] || !is_numeric($input['number'])) {
            return returnJson(1, '金额填写错误');
        }
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        if (!$input['sids']) {

            return returnJson(1, '请选择学员');
        }

        $key = "charge-0-{$input['number']}";
        $cache = cache($key);
        if ($cache) {
            return returnJson(1, '为防止重复充值,请1分钟后再试');
        }
        cache($key, 1, 60);
        $all = [];
        foreach ($input['sids'] as $value) {
            foreach ($value as $val) {
                $userStu = UserStudent::getOne(['sid' => $val]);
                if ($userStu) {
                    $all[] = [
                        'uid' => $userStu['uid'],
                        'sid' => $val
                    ];
                }
            }
        }
        if ($all) {
            foreach ($all as $value) {
                UserModel::changeMoney($value['uid'], 2, $input['number'], $input['note'], '', [
                    'manager_name' => $this->manager['name'],
                    'is_charge' => 1
                ], $value['sid']);
            }
        }

        return returnJson(0, '充值成功');
    }

    /**
     * 所有学生
     * @return \think\response\Json
     */
    public function student_all()
    {
        $student = \app\common\model\Student::getAll([], '', 'id,name');
        return returnJson(0, '', $student);
    }

    /**
     * 绑定学员
     * @return \think\response\Json
     */
    public function student_bind()
    {
        $uids = \app\common\model\UserStudent::getColumn(['sid' => input('sid', 0)], 'uid');
        if ($uids) {
            $user_student = \app\common\model\User::getAll(['id' => ['in', $uids]], '', 'id,nickname');
        } else {
            $user_student = [];
        }
        return returnJson(0, '', $user_student);
    }

    /* 打款 */
    public function atmConfirm()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, '提现记录不存在');
        }
        $log = WithdrawalModel::getOne([
            'id' => $input['id']
        ]);
        if (!$log || $log['status'] != 1) {
            return returnJson(1, '提现记录已处理');
        }
        if ($log['bank_name'] == '微信钱包') {
            $userInfo = UserModel::getOneById($log['uid']);
            $result = PayService::S(['mall_id' => 1])->qiyePay($log, $userInfo);
            if ($result === true) {
                $save = [
                    'status' => 2,
                    'update_time' => time()
                ];
                $res = WithdrawalModel::where('id', $log['id'])->update($save);
                if ($res) {
                    return returnJson(0, '审核成功');
                } else {
                    return returnJson(0, '审核失败请重试');
                }
            } else {
                return returnJson(0, $result);
            }

        } else {
            $save = [
                'status' => 2,
                'update_time' => time()
            ];
            $res = WithdrawalModel::where('id', $log['id'])->update($save);
            if ($res) {
                return returnJson(0, '审核成功');
            } else {
                return returnJson(0, '审核失败请重试');
            }
        }
    }

    /* 拒绝 */
    public function atmRefund()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, '提现记录不存在');
        }
        $log = WithdrawalModel::getOne([
            'id' => $input['id']
        ]);
        if (!$log || $log['status'] != 1) {
            return returnJson(1, '提现记录已处理');
        }
        $save = [
            'status' => 3,
            'update_time' => time()
        ];
        $res = WithdrawalModel::where('id', $log['id'])->update($save);
        if ($res) {
            UserModel::changeMoney($log['uid'], 1, $log['money'], '提现退回', false, [
                'manager_name' => $this->manager['name']
            ]);
            return returnJson(0, '已退回');
        } else {
            return returnJson(0, '处理失败请重试');
        }
    }
}
